package controller;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
@RequestMapping("/file")
public class DownloadController {

    @RequestMapping("/download1")
    public void download1(HttpServletResponse response){
        System.out.println("DownloadController.download1()");
        response.setHeader("content-disposition","attachment;filename=Spring.zip");

        OutputStream out=null;
        InputStream in=null;

        Resource resource=new ClassPathResource("download/Spring.zip");

        try {
            in=resource.getInputStream();
            out=response.getOutputStream();

//            String realPath=application.getRealPath("download/Spring.zip");

            byte[] b=new byte[2048];

            int n;

            while((n=in.read(b))!=-1){
                out.write(b,0,n);
            }




        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    @RequestMapping("/download2")
    public ResponseEntity<byte[]> download2() throws Exception {
        System.out.println("DownloadController.download2()");

        HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment","Spring.zip");

        Resource resource=new ClassPathResource("download/Spring.zip");

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(resource.getFile()),
                                          headers,
                                          HttpStatus.OK);

    }

















}
